package org.gl.android.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.gl.android.base.R;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ImageUploadActivity extends Activity
{
  public final int RequestCode_ImageUpload = 520;
  public final static String ImageUpload = "uploadUrl";
  public final static String ImageUploadResuleExtraKey = "uploadResult";
  
  private TextView mText1;
  private TextView mText2;
  private View mButton;
  private final int RequestCode_Carmer = 1;
  private final int RequestCode_Gallay = 2;
  private String TAG = "ImageUploadActivity";
  private String picPath;
  private Bitmap bitmap;
  /**
   * for test
   */
  String uploadUrl = "http://www.chanceit.cn:8081/fileload/servlet/Uploadify";
  Handler handler = new Handler()
  {
    @Override
    public void handleMessage(Message msg)
    {
      super.handleMessage(msg);
      switch (msg.what)
      {
        case 0:

          break;
        case 1:
          findViewById(R.id.progressBar1).setVisibility(View.VISIBLE);
          break;
        case 2:
          findViewById(R.id.progressBar1).setVisibility(View.GONE);
          alert("update fail ,try again");
          mButton.setEnabled(true);
          findViewById(R.id.button).setEnabled(true);
          findViewById(R.id.button1).setEnabled(true);
          break;
        case 3:
          alert("update success,result:" + msg.obj);
          setResult(RequestCode_ImageUpload,
              getIntent().putExtra(ImageUploadResuleExtraKey, msg.obj.toString()));
          onBackPressed();
          break;

        default:
          break;
      }
    }
  };

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.upload_image);
    mButton = findViewById(R.id.myButton);
    mButton.setEnabled(false);
    mButton.setOnClickListener(new View.OnClickListener()
    {
      public void onClick(View v)
      {
        uploadUrl = (getIntent().getStringExtra(ImageUpload) == null ? uploadUrl
            : getIntent().getStringExtra(ImageUpload));
        mText1 = (TextView) findViewById(R.id.myText2);
        mText1.setText("//" + picPath);
        mText2 = (TextView) findViewById(R.id.myText3);
        mText2.setText("//" + uploadUrl);
        mButton.setEnabled(false);
        findViewById(R.id.button).setEnabled(false);
        findViewById(R.id.button1).setEnabled(false);
        new Thread()
        {
          public void run()
          {
            handler.sendEmptyMessage(1);
            final String result = UploadUtil.uploadFile(new File(
                picPath), uploadUrl);
            if (TextUtils.isEmpty(result))
            {
              handler.sendEmptyMessage(2);
            } else
            {
              handler.sendMessage(handler.obtainMessage(3, result));
            }
          };
        }.start();

      }
    });

    findViewById(R.id.button).setOnClickListener(
        new View.OnClickListener()
        {
          public void onClick(View v)
          {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// �������
            startActivityForResult(intent, RequestCode_Carmer);
          }

        });
    findViewById(R.id.button1).setOnClickListener(
        new View.OnClickListener()
        {
          public void onClick(View v)
          {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, RequestCode_Gallay);
          }

        });
  }

  protected void onActivityResult(int requestCode, int resultCode,
      Intent data)
  {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK)
    {
      destoryBitmap();
      switch (requestCode)
      {
        case RequestCode_Carmer:
          String sdStatus = Environment.getExternalStorageState();
          if (!sdStatus.equals(Environment.MEDIA_MOUNTED))
          {
            Log.v("TestFile",
                "SD card is not avaiable/writeable right now.");
            alert("SD card is not avaiable/writeable right now.");
            return;
          }

          Bundle bundle = data.getExtras();
          bitmap = (Bitmap) bundle.get("data");
          FileOutputStream b = null;
          String tempPath = Environment.getExternalStorageDirectory()
              + "/temp.jpg";
          String fileName = tempPath;
          picPath = fileName;
          picPath = fileName;

          try
          {
            b = new FileOutputStream(fileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
          } catch (FileNotFoundException e)
          {
            e.printStackTrace();
          } finally
          {
            try
            {
              b.flush();
              b.close();
            } catch (IOException e)
            {
              e.printStackTrace();
            }
          }

          ((ImageView) findViewById(R.id.imageView))
              .setImageBitmap(bitmap);
          mButton.setEnabled(true);
          break;
        case RequestCode_Gallay:
          Uri uri = data.getData();
          Log.i(TAG, "uri = " + uri);
          try
          {
            String[] pojo =
            { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, pojo, null, null, null);
            if (cursor != null)
            {
              ContentResolver cr = this.getContentResolver();
              int colunm_index = cursor
                  .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
              cursor.moveToFirst();
              String path = cursor.getString(colunm_index);
              if (path.endsWith("jpg") || path.endsWith("png"))
              {
                picPath = path;
                bitmap = BitmapFactory.decodeStream(cr
                    .openInputStream(uri));
                ((ImageView) findViewById(R.id.imageView))
                    .setImageBitmap(bitmap);
              } else
              {
                alert();
              }
            } else
            {
              alert();
            }

          } catch (Exception e)
          {
            e.printStackTrace();
          }
          mButton.setEnabled(true);
          super.onActivityResult(requestCode, resultCode, data);
          break;

        default:
          break;
      }

    } else
    {
      alert();
    }
  }

  private void alert()
  {
    Toast.makeText(getBaseContext(), "pick image fail",
        Toast.LENGTH_SHORT).show();

  }

  private void alert(String s)
  {
    Toast.makeText(getBaseContext(), "" + s, Toast.LENGTH_SHORT).show();

  }

  @Override
  protected void onDestroy()
  {
    destoryBitmap();
    super.onDestroy();
  }

  private void destoryBitmap()
  {
    if (bitmap != null && !bitmap.isRecycled())
    {
      bitmap.recycle();
      bitmap = null;
    }
  }

  /**
   * ��ȡ·���е�ͼƬ��Ȼ����ת��Ϊ���ź��bitmap
   * 
   * @param path
   */
  public String saveBefore(String path)
  {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(path, options);
    options.inJustDecodeBounds = false;
    int be = (int) (options.outHeight / (float) 200);
    if (be <= 0)
      be = 1;
    options.inSampleSize = 4;
    bitmap = BitmapFactory.decodeFile(path, options);
    // savePNG_After(bitmap,path);
    return saveJPGE_After(bitmap, path);
  }

  /**
   * 
   * @param bitmap
   * @param path
   */
  public String saveJPGE_After(Bitmap bitmap, String path)
  {
    File file = new File(path);
    try
    {
      FileOutputStream out = new FileOutputStream(file);
      if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out))
      {
        out.flush();
        out.close();
      }
    } catch (FileNotFoundException e)
    {
      e.printStackTrace();
    } catch (IOException e)
    {
      e.printStackTrace();
    }
    return path;
  }
}
